const ClientRouterProvider = require('../lib/ClientRouterProvider');
const HtmlWebpackPlugin = require('html-webpack-plugin');


const createPugScript = (clientRouterConfig) => `${'script(type= "text/javascript" data-client-router).\n'
+ '    '}${JSON.stringify(clientRouterConfig)};`

class InjectRouterInfoWebpackPlugin {
    constructor(options) {
        this.entry = options.entry;
        if (!this.entry) {
            throw Error('options.entry is required');
        }
    }

    // eslint-disable-next-line class-methods-use-this
    apply(compiler) {
        if (compiler.hooks) {
            compiler.hooks.compilation.tap('inject-router-info-webpack-plugin', (compilation) => {
                const {alias} = compilation.options.resolve;
                const clientRouterConfig = (new ClientRouterProvider(this.entry, {alias})).get();
                HtmlWebpackPlugin.getHooks(compilation).beforeAssetTagGeneration.tapAsync(
                    'inject-router-info-webpack-plugin', // <-- Set a meaningful name here for stacktraces
                    (htmlPluginData, callback) => {
                        htmlPluginData.assets.routerInfo = createPugScript(clientRouterConfig);
                        callback(null, htmlPluginData);
                    },
                );
            });
        } else {
            compiler.plugin('compilation', (compilation) => {
                const {alias} = compilation.options.resolve;
                const clientRouterConfig = (new ClientRouterProvider(this.entry, {alias})).get();
                compilation.plugin('html-webpack-plugin-before-html-generation', (htmlPluginData, callback) => {
                    Object.assign(htmlPluginData.plugin.options, {
                        inlineJs: [createPugScript(clientRouterConfig)],
                    });
                    callback(null, htmlPluginData);
                });
            });
        }
    }
}

module.exports = InjectRouterInfoWebpackPlugin;
